<template>
    <div class="form">
        <div class="formText">
            <el-form :model="form" ref="formRef" label-width="120px" :rules="rules">
                <el-form-item label="分类名称:" prop="name">
                    <el-input v-model="form.name" />
                </el-form-item>

                <el-form-item label="上级分类:">
                    <el-select v-model="value1">
                        <el-option label="无上级分类" />
                        <el-option v-for="item in branchClass" :key="item.value" :label="item.name"
                            :value="item.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="数量单位:">
                    <el-input v-model="form.productUnit" />
                </el-form-item>

                <el-form-item label="排序:">
                    <el-input v-model="form.sort" />
                </el-form-item>

                <el-form-item label="是否显示:">
                    <el-radio-group v-model="showRadio" @change="showGroup(Number(showRadio))">
                        <el-radio label="1">是</el-radio>
                        <el-radio label="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="是否显示在导航栏:">
                    <el-radio-group v-model="navRadio" @change="navGroup(Number(navRadio))">
                        <el-radio label="1">是</el-radio>
                        <el-radio label="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="分类图标:">
                    <el-upload ref="upload" class="upload-demo"
                        action="http://xue.cnkdl.cn:9082/mall-admin/minio/upload" :limit="1" :on-preview="handlePreview"
                        :on-remove="handleRemove" :on-exceed="handleExceed" list-type="picture" accept=".jpg,.png">
                        <el-button type="primary">点击上传</el-button>
                        <template #tip>
                            <div class="el-upload__tip">
                                只能上传jpg/png文件，且不超过100kb
                            </div>
                        </template>
                    </el-upload>
                    <el-dialog v-model="dialogVisible">
                        <img class="img" w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
                </el-form-item>

                <el-form-item label="筛选属性:">
                    <div class="deldiv" v-for="(item, index) in choiceQuantity" :key="item.id">
                        <el-cascader @change="cascader" v-model="contentVal[index]" :options="options" clearable
                            placeholder=" " />
                        <el-button class="del" @click="del(index)">删除</el-button>
                    </div>
                    <div class="add">
                        <el-button type="primary" @click="add">增加</el-button>
                    </div>
                </el-form-item>

                <el-form-item label="关键词:">
                    <el-input v-model="form.keywords" />
                </el-form-item>

                <el-form-item label="分类描述:">
                    <el-input v-model="form.description" autosize type="textarea" />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="onSubmit">提交</el-button>
                    <el-button @click="Reset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox, FormInstance, genFileId, UploadInstance, UploadProps, UploadRawFile, UploadUserFile } from 'element-plus';
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router';
import { createAttrListApi,withAttrListApi, withChildrenListApi } from './api'

const router = useRouter()
const navRadio = ref("0");
const showRadio = ref("0");

// form数据
const formRef = ref<FormInstance>()
// 默认数据
const form = reactive<IcreateAttrList>({
    description: "",//描述
    icon: "",
    keywords: "",//关键字
    name: "",//名称
    navStatus: 0,//导航栏状态
    parentId: 0,
    productAttributeIdList: [0],
    productUnit: "",//数量单位
    showStatus: 0,//显示状态
    sort: 0//排序
})


// 是否显示在导航栏单选
form.navStatus = Number(navRadio.value);
const navGroup = (navRadio: number) => {
    form.navStatus = navRadio;
};
// 是否显示单选
form.showStatus = Number(showRadio.value);
const showGroup = (showRadio: number) => {
    form.showStatus = showRadio;
};

// 有无分类数据
const value1 = ref('无上级分类')
const branchClass = ref<{ name: string; value: number }[]>()

// 请求一级分类及子分类
withChildrenListApi().then((res) => {
    // console.log(res.data);
    branchClass.value = res.data.map(item => ({
        name: item.name,
        value: item.id,

    }))
})

//获取所有商品属性分类及其下属性
withAttrListApi().then((res) => {
    console.log("下属", res);
    options.value = res.data.map(item => ({
        label: item.name,
        value: item.id,
    }))
})

// 筛选数据
const options = ref<{
    label: string; value: number,
}[]>([])
const contentVal = ref([])

const cascader = () => {
    form.productAttributeIdList = contentVal.value.map(item => (item[0]))
    console.log(form.productAttributeIdList);

}






// 点击修改选择框
let choiceQuantity = reactive([{
    id: 1,
    value: ''
}])
// 点击添加
const add = () => {
    choiceQuantity.push({
        id: choiceQuantity[choiceQuantity.length - 1].id++,
        value: ''
    })
}
// 点击删除
const del = (index: number) => {
    if (choiceQuantity.length !== 1) {
        choiceQuantity.splice(index, 1)
        form.productAttributeIdList
            .splice(index, 1)
    }

}

// 图片数据
const upload = ref<UploadInstance>();


// 点击文件放大
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

// 点击删除文件
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    return ElMessageBox.confirm(
        `确定要删除图片 ${uploadFile.name} 吗?`
    ).then(
        () => true,
        () => false
    )
}
// 点击放大文件
const handlePreview: UploadProps['onPreview'] = (file) => {
    console.log("1234", file.url);
    dialogImageUrl.value = file.url!
    dialogVisible.value = true
}
const handleExceed: UploadProps['onExceed'] = (files) => {
    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload.value!.handleStart(file)



}




// 规则
const rules = reactive({
    name: [{ required: true, trigger: "blur", message: "请填写分类名称" }],

})


// 添加
const addProductCate = () => {
    ElMessageBox.confirm('确定要提交数据吗', '添加商品分类', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning",
    }).then(() => {
        createAttrListApi((form)).then((res) => {
         if(res.code===200){
            ElMessage.success("添加成功")
            router.push('/pms/productCate')
         }
        })
    }).catch(() => {
        ElMessage.error('提交失败,请重新提交')
    })

}

// 点击提交
const onSubmit = () => {
    addProductCate()
}


const Reset = () => {
    form.description = "";
    form.icon = "";
    form.keywords = "";
    form.name = "";
    form.navStatus = 0;
    form.parentId = 0;
    form.productUnit = "";
    form.showStatus = 0;
    form.sort = 0;
    choiceQuantity = [];
    form.productAttributeIdList = [];
    value1.value = "无上级分类";
    upload.value!.clearFiles()

}
</script>

<style lang="less" scoped>
.form {
    // background-color: #cFc;
    box-sizing: border-box;
    padding: 35px 35px 15px 35px;
    // margin: 25px;
    width: 790px;
    margin: 30px auto 0px;
    border: 1px solid rgb(231, 231, 231);

    .formText {
        padding: 20px;

        :deep(.el-form-item) {
            width: 100%;
            // height: 40px;
            margin-bottom: 22px;

            .asterisk-left {
                // height: 72px !important;
                margin-bottom: 54px;
            }

            .upload-demo {
                width: 100%
            }

            .el-form-item__content {
                // height: 40px;


                .el-input {
                    height: 40px;
                }
            }

            .el-form-item__label {
                width: 150px !important;
                line-height: 40px;
            }
        }

        .deldiv {
            margin-bottom: 22px;

            .del {
                margin-left: 20px;

            }
        }


        .add {
            width: 100%;
            margin-bottom: 22px;
        }

        .img {
            width: 100%;
        }
    }
}
</style>